package com.zline.foodraise.ui.activity;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.SupportListAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.CustomerUserBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.listener.RecyclerOnScrollListener;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.DrawableDividerItemDecoration;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/8/6.
 * 众筹用户关注列表
 */
@EActivity(R.layout.activity_support_list)
public class ProjectAttentionListActivity extends ZlineActivity implements RecyclerItemClicked {
    private static final String LOG_TAG = ProjectAttentionListActivity.class.getSimpleName();
    @ViewById(R.id.support_list_recyclerView)
    RecyclerView recyclerView;
    @ViewById(R.id.support_list_srl)
    SwipeRefreshLayout swipeRefreshLayout;
    SparseArray<CustomerUserBean> sparseArray;
    @Bean
    SupportListAdapter adapter;
    @Bean
    HttpUtil httpUtil;
    @Bean
    HttpOperator httpOperator;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    //当前页
    int currt_page = 1;
    //共多少页
    int pageCount;
    int position;
    @Bean
    HttpDataParsing httpDataParsing;
    LinearLayoutManager layoutManager;
    long toUserId;
    //动态ID
    @Extra
    long projectId;
    @Pref
    AppPref_ appPref;
    //登陆后刷新关注状态
    boolean refresh = false;

    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.ex_no_data_rl)
    RelativeLayout no_data_rl;
    @Bean
    NetworkUtil networkUtil;
    //是否加载失败
    boolean loadFail = false;
    //第一次加载数据
    boolean firstLoad = true;
    //加载更多
    boolean loadMore = false;

    @AfterViews
    void doSomeAfterViews() {
        sparseArray = new SparseArray<CustomerUserBean>();
        initView();
        requestData();
    }


    //请求数据
    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            requestAttentionList();
        } else {
            showLoadFailView(true);
            TUtil.showShort(ProjectAttentionListActivity.this, R.string.no_network);
        }
    }


    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        loadFail = isException;
        if (isException) {
            exception_fl.setVisibility(View.VISIBLE);
            exception_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            exception_rl.setVisibility(View.GONE);
        }
    }

    //是否显示暂无数据
    void showNoDataView(boolean noData) {
        if (noData) {
            exception_fl.setVisibility(View.VISIBLE);
            no_data_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            no_data_rl.setVisibility(View.GONE);
        }
    }

    void initView() {
        initSwipRefreshLayout();
        initRecyclerView();
    }

    //初始化RecyclerView
    void initRecyclerView() {
        recyclerView.addItemDecoration(new DrawableDividerItemDecoration(getResources().getDrawable(R.drawable.recycleview_divider), true, true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setHasFixedSize(true);
        recyclerView.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter.setAdapterData(sparseArray);
        adapter.setRecycleItemClickListener(this);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                if (currt_page < pageCount) {
                    //检查网络
                    if (networkUtil.isNetworkAvailable()) {
                        currt_page++;
                        showRecyclerFoot(true);
                        loadMore = true;
                        requestAttentionList();
                    } else {
                        TUtil.showShort(ProjectAttentionListActivity.this, R.string.no_network);
                    }
                }

            }
        });
    }

    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //检查网络
                if (networkUtil.isNetworkAvailable()) {
                    currt_page = 1;
                    requestAttentionList();
                } else {
                    stopRefresh();
                    TUtil.showShort(ProjectAttentionListActivity.this, R.string.no_network);
                }


            }
        });
    }

    //请求关注列表
    void requestAttentionList() {
        httpOperator.requestProjectAttentionList(httpUtil, projectId,
                Constant.PAGE_ROWS_NUMBER, currt_page, requestAttentionHandler);
    }


    //获取关注列表回调
    AsyncHttpResponseHandler requestAttentionHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestAttentionHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        sparseArray = httpDataParsing.getProjectAttentionList(response);
                        getPageCount(response);
                        if (swipeRefreshLayout.isRefreshing() || refresh) {
                            refreshData(sparseArray);
                        } else {
                            loadMoreData(sparseArray);
                        }

                    } else {
                        loadFailInfo();
                        if (firstLoad) {
                            showLoadFailView(true);
                        } else {
                            httpErro.showCommonErroResult(resultCode);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    dissLoadingDialog();
                    firstLoad = false;
                }
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            loadFailInfo();
            dissLoadingDialog();
            if (firstLoad) {
                showLoadFailView(true);
            }
        }
    };


    //改变关注状态
    void changeAttentionStatus(int position) {
        if (adapter.getArrys().size() > 0) {
            toUserId = adapter.getArrys().get(position).getUserId();
            int operatorType = adapter.getArrys().get(position).getIsAttention() == 1 ? 0 : 1;
            if (operatorType == 1) {
                if (networkUtil.isNetworkAvailable()) {
                    httpOperator.changeAttentionStatus(httpUtil, toUserId, operatorType, changeAttentionStatusHandler);
                } else {
                    TUtil.showShort(ProjectAttentionListActivity.this, R.string.no_network);
                }
            } else {
                openCancelAttentionDialog();
            }
        }
    }

    //关注状态改变回调
    AsyncHttpResponseHandler changeAttentionStatusHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs____changeAttentionStatusHandler______" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        refreshAttentionStatus();
                    } else {
                        httpErro.showAttentionErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);

        }
    };


    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    //刷新数据
    void refreshData(SparseArray<CustomerUserBean> userArray) {
        if (loadFail) {
            showLoadFailView(false);
        }
        adapter.setAdapterData(userArray);
        adapter.notifyDataSetChanged();
        stopRefresh();
        isNoDataException();
    }

    //加载更多数据
    void loadMoreData(SparseArray<CustomerUserBean> userArray) {
        loadMore = false;
        if (currt_page == pageCount) {
            showRecyclerFoot(false);
        }
        if (loadFail) {
            showLoadFailView(false);
        }
        adapter.addAll(userArray);
        if (currt_page == 1) {
            isNoDataException();
        }
    }

    //是否显示暂时没有数据
    void isNoDataException() {
        int size = adapter.getArrys().size();
        if (size == 0) {
            showNoDataView(true);
        } else {
            showNoDataView(false);
        }
    }

    //是否显示正在加载
    void showRecyclerFoot(boolean bol) {
        if (adapter != null) {
            adapter.setFootEnable(bol);
            adapter.notifyItemChanged(adapter.getArrys().size());
        }
    }

    //加载失败时候情况处理
    void loadFailInfo() {
        stopRefresh();
        if (loadMore) {
            currt_page--;
        }
        if (adapter.getFootEnable()) {
            showRecyclerFoot(false);
        }
        firstLoad = false;
    }

    //分页查找共多少页
    @Background
    void getPageCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.USER_BEAN_PAGE);
            pageCount = jsonObject.getInt(Constant.PAGE_COUNT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    //取消关注对话框
    void openCancelAttentionDialog() {
        new MaterialDialog.Builder(this)
                .title(R.string.warm_prompt)
                .titleGravity(GravityEnum.CENTER)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        if (networkUtil.isNetworkAvailable()) {
                            httpOperator.changeAttentionStatus(httpUtil, toUserId, 0, changeAttentionStatusHandler);
                        } else {
                            TUtil.showShort(ProjectAttentionListActivity.this, R.string.no_network);
                        }
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {

                    }
                })
                .content(R.string.cancel_attention_dialog_content)
                .positiveText(R.string.ok)
                .negativeText(R.string.cancel)
                .show();
    }


    //刷新关注状态
    void refreshAttentionStatus() {
        CustomerUserBean user = adapter.getArrys().get(position);
        user.setIsAttention(user.getIsAttention() == 1 ? 0 : 1);
        adapter.getArrys().put(position, user);
        adapter.notifyItemChanged(position);
    }

    @Click({R.id.app_common_header_left_icon_iv, R.id.reload_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.reload_tv:
                requestData();
                break;
            default:
                break;
        }
    }


    //未登录要先登录后刷新商品关注状态
    @OnActivityResult(Constant.PROJECT_ATTENTION_REQUEST_CODE)
    void onActivityResult(int resultCode) {
        switch (resultCode) {
            case Constant.LOGIN_RESULT_CODE:
                currt_page = 1;
                refresh = true;
                requestData();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRecyclerItemClicked(int position) {
        this.position = position;
        if (appPref.userId().get() > 0) {
            changeAttentionStatus(position);
        } else {
            LoginActivity_.intent(this).startForResult(Constant.PROJECT_ATTENTION_REQUEST_CODE);
        }

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {
        CustomerUserBean userBean = adapter.getArrys().get(position);
        if (userBean != null) {
            long userId = userBean.getUserId();
            PersonalHomePageActivity_.intent(this).userId(userId).start();
        }

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {

    }
}
